<template>
	<div>
		<el-form :model="state.form" ref="formRef">
			<el-form-item label="商品规格">
				<div style="width: 100%; box-sizing: border-box; border: 1px #ccc solid; padding: 0 10px 10px 10px">
					<div v-for="(item, index) in state.form.specDatas" :key="index" style="width: 100%">
						<div style="display: flex">
							<div style="width: 4.5em; padding: 10px 0">{{ item.parentSpecName }}:</div>

							<div style="display: flex; width: calc(100% - 12em); overflow-x: auto; overflow-y: hidden; padding: 10px 0">
								<div
									style="padding: 0 5px"
									v-for="(w, i) in item.specNames"
									:key="i"
									class="spec-box"
									@mouseenter="w.isShow = true"
									@mouseleave="w.isShow = false"
								>
									<el-icon v-if="w.isShow && item.specNames.length > 1 && !disabled" class="spec-icon" @click="handleSpecDel(item, i, w)">
										<CircleClose />
									</el-icon>
									<el-input
										:disabled="disabled"
										v-model.trim="w.specName"
										style="width: 160px"
										placeholder="可自由编辑"
										:class="{
											warnstyle: item.specNames.filter(o => o.specName === w.specName).length > 1
										}"
										maxlength="32"
										@change="handleChange(item, w.specName, w, i, index)"
									/>
								</div>
							</div>

							<div
								v-if="!disabled"
								style="color: cornflowerblue; cursor: pointer; height: 52px; width: 6em; display: flex; align-items: center; margin-left: 20px"
								@click="handleAdd(item)"
							>
								<el-icon> <CirclePlus /> </el-icon>添加规格值
							</div>
						</div>
					</div>
				</div>
			</el-form-item>

			<el-form-item label="规格明细">
				<div style="width: 100%; min-height: 100px; border: 1px #ccc solid; padding: 10px">
					<el-table
						:data="checkMerchantGoodsSkus"
						:header-cell-style="{ 'text-align': 'center', 'font-size': '13px' }"
						:cell-style="{ 'text-align': 'center', 'font-size': '13px' }"
						border
						style="width: 100%"
					>
						<el-table-column type="index" width="50" />
						<el-table-column
							v-for="(item, index) in state.form.specDatas"
							:key="item.field"
							:prop="item.field"
							:label="item.parentSpecName"
							show-overflow-tooltip
							width="200"
						/>
						<el-table-column prop="image" label="预览图" width="90">
							<template #default="{ row }">
								<el-image style="width: 60px; height: 60px" :preview-src-list="[row.image]" :src="row.image" :preview-teleported="true" />
							</template>
						</el-table-column>
						<el-table-column prop="skuCode" label="商品编码" width="240">
							<template #header>
								<div style="display: flex; justify-content: center; align-items: center"><span style="color: red">*</span> 商品编码</div>
							</template>
							<template #default="{ row, $index }">
								<div style="display: flex; align-items: center; justify-content: center; width: 100%; gap: 5px">
									<el-tooltip :content="row.skuCode" placement="top">
										<el-text type="info" class="a-link">{{ row.skuCode }}</el-text>
									</el-tooltip>

									<el-button v-if="!disabled" type="primary" link>修改</el-button>
								</div>
							</template>
						</el-table-column>
						<el-table-column prop="supplyPrice" label="供货价">
							<template #header>
								<div style="display: flex; justify-content: center; align-items: center"><span style="color: red">*</span> 供货价</div>
							</template>
						</el-table-column>
						<el-table-column prop="quantity" label="库存">
							<template #header>
								<div style="display: flex; justify-content: center; align-items: center"><span style="color: red !important">*</span> 库存</div>
							</template>
						</el-table-column>
						<el-table-column prop="weight" label="重量" show-overflow-tooltip>
							<template #header>
								<div style="display: flex; justify-content: center; align-items: center"><span style="color: red">*</span> 重量(kg)</div>
							</template>
						</el-table-column>
						<el-table-column prop="freightTemplateName" label="发货区域" width="160" show-overflow-tooltip />
					</el-table>
				</div>
			</el-form-item>
		</el-form>
		<el-button @click="handleSubmit">Submit</el-button>
	</div>
</template>

<script setup>
import { reactive, ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
const formRef = ref()
const state = reactive({
	form: {
		specDatas: [
			{
				parentSpecName: '颜色',
				field: 'colour',
				specNames: [
					{
						specName: '透明塑料花盆-中号-1个装（无白色部分，只有透明的杯子）',
						jdSaleTplLabel: null,
						imgUrl: 'https://resources.laipuhuo.com/Image/5b4a6da3-594d-4dee-923a-f9c2a2193463.jpg',
						isCheck: true,
						skuIds: ['d9edb8fc1f21438dabbc08f897116361']
					},
					{
						specName: '透明塑料花盆-小号-1个装（无白色部分，只有透明的杯子）',
						jdSaleTplLabel: null,
						imgUrl: 'https://resources.laipuhuo.com/Image/ee158a0f-7a0a-4660-b8c5-8ff1cb12e9df.jpg',
						isCheck: true,
						skuIds: ['f3acda1a112a494298a6022ff897b21b']
					}
				]
			},
			{
				parentSpecName: '尺寸',
				field: 'skuName',
				specNames: [
					{
						specName: '无白色部分 只有透明',
						jdSaleTplLabel: null,
						imgUrl: 'https://resources.laipuhuo.com/Image/5b4a6da3-594d-4dee-923a-f9c2a2193463.jpg',
						isCheck: true,
						skuIds: ['d9edb8fc1f21438dabbc08f897116361', 'f3acda1a112a494298a6022ff897b21b']
					}
				]
			}
		],
		merchantGoodsSkuList: [
			{
				colour: '透明塑料花盆-中号-1个装（无白色部分，只有透明的杯子）',
				skuName: '无白色部分 只有透明',
				status: 0,
				weight: 0.0036,
				quantity: 723,
				image: 'https://resources.laipuhuo.com/Image/5b4a6da3-594d-4dee-923a-f9c2a2193463.jpg',
				skuSpecPic: null,
				supplyPrice: 0.325,
				multiPrice: null,
				price: 0,
				salePrice: 0,
				patentPrice: null,
				skuCode: 'ZZZXB-002',
				skuId: 'd9edb8fc1f21438dabbc08f897116361',
				spuId: '77040c2f3ff840a7ad11530c5438ca4b',
				skuPreSaleTime: null,
				isCheck: true,
				colourParentSpec: '颜色',
				skuNameParentSpec: '尺寸',
				unit: null,
				insideSkuId: '',
				thirdSkuId: null,
				isAutoCreated: false,
				isMerchantCreate: false,
				freightTemplateId: 'b5c777a3-0f6b-439b-ae2d-6a8d9af59df6',
				freightTemplateName: '义乌',
				skuFrom: null,
				erpStyleCode: null,
				newSkuId: null,
				skuIsEdit: false,
				newSupplyPrice: 0,
				isFreeShipped: false,
				freightAmount: 0,
				basicSupplyPrice: 2.625,
				sort: 0,
				saleAttrs: null,
				saleAttrsName: null
			},
			{
				colour: '透明塑料花盆-小号-1个装（无白色部分，只有透明的杯子）',
				skuName: '无白色部分 只有透明',
				status: 0,
				weight: 0.0446,
				quantity: 379,
				image: 'https://resources.laipuhuo.com/Image/ee158a0f-7a0a-4660-b8c5-8ff1cb12e9df.jpg',
				skuSpecPic: null,
				supplyPrice: 0.85,
				multiPrice: null,
				price: 0,
				salePrice: 0,
				patentPrice: null,
				skuCode: 'TMSLHP-001',
				skuId: 'f3acda1a112a494298a6022ff897b21b',
				spuId: '77040c2f3ff840a7ad11530c5438ca4b',
				skuPreSaleTime: null,
				isCheck: true,
				colourParentSpec: '颜色',
				skuNameParentSpec: '尺寸',
				unit: null,
				insideSkuId: '',
				thirdSkuId: null,
				isAutoCreated: false,
				isMerchantCreate: false,
				freightTemplateId: 'b5c777a3-0f6b-439b-ae2d-6a8d9af59df6',
				freightTemplateName: '义乌',
				skuFrom: null,
				erpStyleCode: null,
				newSkuId: null,
				skuIsEdit: false,
				newSupplyPrice: 0,
				isFreeShipped: false,
				freightAmount: 0,
				basicSupplyPrice: 3.15,
				sort: 0,
				saleAttrs: null,
				saleAttrsName: null
			}
		]
	}
})


// 判断字段是否有重复
const isRepeat = (arr, key) => {
  let mapArr = arr.map((item) => item[key])
  let len = new Set(mapArr).size
  return mapArr.length !== len
}

// 选中的SKU
const checkMerchantGoodsSkus = computed(() => {
	if (!state.form.merchantGoodsSkuList) return []

	let merchantGoodsSkuListData = state.form.merchantGoodsSkuList.filter(e => e.isCheck)

	// console.log(merchantGoodsSkuListData, '8888')
	return merchantGoodsSkuListData
})

//新增规格值
const handleAdd = (item) => {
  if (item.specNames.some((i) => i.specName == '')) {
    ElMessage.error('请先填写规格值')
    return
  }
  if (isRepeat(item.specNames, 'specName')) {
    ElMessage.error(item.parentSpecName + '有重复值！')
    return
  }
  item.specNames.push({
    specName: '',
    imgUrl: '',
    add: '1',
    skuIds: []
  })
  // moveSkuSort()
}

//删除商品规格
const handleSpecDel = (item, i, w) => {
  state.form.merchantGoodsSkuList = state.form.merchantGoodsSkuList.filter(
    (item) => !w.skuIds.includes(item.skuId)
  )
  colourListChenga(state.colour)
  item.specNames.splice(i, 1)
  moveSkuSort()
}

const colourListChenga = (val) => {
  if (val) {
    state.merchantGoodsSkuListCopy = state.form.merchantGoodsSkuList.filter(
      (item) => item.colour == val
    )
  } else {
    state.form.merchantGoodsSkuList.forEach((item) => {
      item.isChange = false
    })
    state.merchantGoodsSkuListCopy = state.form.merchantGoodsSkuList
  }
}

//规格改变/修改规格
const handleChange = (item, val, w, i, specIndex) => {
  const curItem = item
  const repeate = isRepeat(curItem.specNames, 'specName')
  if (repeate) {
    ElMessage.warning('名称存在重复，请重新输入')
  }
  if (w?.add) {
    if (w?.addId) {
      w.skuIds.forEach((skuId) => {
        var skuInfo = state.form.merchantGoodsSkuList.find(
          (s) => s.skuId == skuId
        )
        if (skuInfo) {
          skuInfo[item.field] = val
          if (item.field != 'skuName') skuInfo.image = w.imgUrl
        }
      })
    } else {
      let obj = {
        colour: '',
        colourParentSpec: '',
        image: '',
        insideSkuId: '',
        isAutoCreated: false,
        isCheck: true,
        isMerchantCreate: false,
        multiPrice: null,
        price: null,
        quantity: null,
        salePrice: null,
        skuCode: null,
        skuId: '',
        skuName: val,
        skuNameParentSpec: '',
        skuPreSaleTime: null,
        skuSpecPic: null,
        spuId: "77040c2f3ff840a7ad11530c5438ca4b",
        status: 1,
        supplyPrice: null,
        thirdSkuId: null,
        unit: null,
        weight: null
      }
      const tpName = item.parentSpecName
      if (item.field == 'colour' && (w.specName || w.imgUrl)) {
        const otherTpName = state.form.specDatas.find(
          (j) => j.field === 'skuName'
        )
        w.skuIds = []
        let specNamesObj = state.form.specDatas.find(
          (item) => item.field == 'skuName'
        )
        if (specNamesObj) {
          specNamesObj?.specNames
            .filter((item) => item.specName != '')
            .forEach((item) => {
              let addId = getUuid()
              w.skuIds.push(addId)
              w.addId = addId
              item?.skuIds.push(addId)
              obj.colour = val
              obj.image = w.imgUrl
              obj.skuName = item.specName
              obj.skuId = addId
              obj.add = w.add
              obj.colourParentSpec = tpName ? tpName : ''
              obj.skuNameParentSpec = otherTpName
                ? otherTpName.parentSpecName
                : ''
              state.form.merchantGoodsSkuList.push({ ...obj })
            })
        } else {
          let addId = getUuid()
          w.skuIds.push(addId)
          w.addId = addId
          obj.colour = val
          obj.image = w.imgUrl
          obj.skuName = ''
          obj.skuId = addId
          obj.add = w.add
          obj.colourParentSpec = tpName ? tpName : ''
          obj.skuNameParentSpec = otherTpName ? otherTpName.parentSpecName : ''
          state.form.merchantGoodsSkuList.push({ ...obj })
        }
      } else if (item.field == 'skuName' && (w.specName || w.imgUrl)) {
        const otherTpName = state.form.specDatas.find(
          (j) => j.field === 'colour'
        )
        w.skuIds = []
        let specNamesObj = state.form.specDatas.find(
          (item) => item.field == 'colour'
        )

        if (specNamesObj) {
          specNamesObj.specNames
            .filter((item) => item.specName != '')
            .forEach((item) => {
              let addId = getUuid()
              w.skuIds.push(addId)
              w.addId = addId
              item?.skuIds.push(addId)
              obj.image = item.imgUrl
              obj.colour = item.specName
              obj.skuName = val
              obj.skuId = addId
              obj.add = w.add
              obj.colourParentSpec = otherTpName
                ? otherTpName.parentSpecName
                : ''
              obj.skuNameParentSpec = tpName ? tpName : ''
              state.form.merchantGoodsSkuList.push({ ...obj })
            })
        } else {
          let addId = getUuid()
          w.skuIds.push(addId)
          w.addId = addId

          item?.skuIds.push(addId)
          obj.image = ''
          obj.colour = ''
          obj.skuName = val
          obj.skuId = addId
          obj.add = w.add
          obj.skuNameParentSpec = otherTpName ? otherTpName.parentSpecName : ''
          state.form.merchantGoodsSkuList.push({ ...obj })
        }
      }
    }
  } else {
    if (item.field == 'colour') {
      w.skuIds.forEach((skuId) => {
        let skuInfo = state.form.merchantGoodsSkuList.find(
          (s) => s.skuId == skuId
        )
        if (skuInfo) {
          skuInfo[item.field] = val
          skuInfo.image = w.imgUrl
        }
      })
    } else {
      w.skuIds.forEach((skuId) => {
        let skuInfo = state.form.merchantGoodsSkuList.find(
          (s) => s.skuId == skuId
        )
        if (skuInfo) {
          skuInfo[item.field] = val
        }
      })
    }
  }

  state.colourList = new Set([
    ...state.form.merchantGoodsSkuList.map((item) => item.colour)
  ])
  colourListChenga(state.colour)
}


//随机id
const getUuid = () => {
  var s = []
  var hexDigits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = '4'
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1)
  s[8] = s[13] = s[18] = s[23] = '-'
  let uuid = s.join('')
  return uuid
}


</script>

<style scoped lang="scss">
.spec-box {
	position: relative;

	.spec-icon {
		position: absolute;
		right: 0px;
		top: -5px;
		color: #b1b3b8;
		z-index: 2;
	}
}
</style>
